home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / ViePratique / ArchiFacile / ArchiFacileSetup.exe / {app} / nw.pak / Unnamed File 000157.txt < prev    next >
Text File  |  2014-10-14  |  15KB  |  470 lines

  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4.  
  5. // Copyright (c) 2013 The Chromium Authors. All rights reserved.
  6. // Use of this source code is governed by a BSD-style license that can be
  7. // found in the LICENSE file.
  8.  
  9. /**
  10.  * @fileoverview Assertion support.
  11.  */
  12.  
  13. /**
  14.  * Simple common assertion API
  15.  * @param {*} condition The condition to test.  Note that this may be used to
  16.  *     test whether a value is defined or not, and we don't want to force a
  17.  *     cast to Boolean.
  18.  * @param {string=} opt_message A message to use in any error.
  19.  */
  20. function assert(condition, opt_message) {
  21.   'use strict';
  22.   if (!condition) {
  23.     var msg = 'Assertion failed';
  24.     if (opt_message)
  25.       msg = msg + ': ' + opt_message;
  26.     throw new Error(msg);
  27.   }
  28. }
  29.  
  30.  
  31. /**
  32.  * The global object.
  33.  * @type {!Object}
  34.  * @const
  35.  */
  36. var global = this;
  37.  
  38. /**
  39.  * Alias for document.getElementById.
  40.  * @param {string} id The ID of the element to find.
  41.  * @return {HTMLElement} The found element or null if not found.
  42.  */
  43. function $(id) {
  44.   return document.getElementById(id);
  45. }
  46.  
  47. /**
  48.  * Add an accessible message to the page that will be announced to
  49.  * users who have spoken feedback on, but will be invisible to all
  50.  * other users. It's removed right away so it doesn't clutter the DOM.
  51.  * @param {string} msg The text to be pronounced.
  52.  */
  53. function announceAccessibleMessage(msg) {
  54.   var element = document.createElement('div');
  55.   element.setAttribute('aria-live', 'polite');
  56.   element.style.position = 'relative';
  57.   element.style.left = '-9999px';
  58.   element.style.height = '0px';
  59.   element.innerText = msg;
  60.   document.body.appendChild(element);
  61.   window.setTimeout(function() {
  62.     document.body.removeChild(element);
  63.   }, 0);
  64. }
  65.  
  66. /**
  67.  * Calls chrome.send with a callback and restores the original afterwards.
  68.  * @param {string} name The name of the message to send.
  69.  * @param {!Array} params The parameters to send.
  70.  * @param {string} callbackName The name of the function that the backend calls.
  71.  * @param {!Function} callback The function to call.
  72.  */
  73. function chromeSend(name, params, callbackName, callback) {
  74.   var old = global[callbackName];
  75.   global[callbackName] = function() {
  76.     // restore
  77.     global[callbackName] = old;
  78.  
  79.     var args = Array.prototype.slice.call(arguments);
  80.     return callback.apply(global, args);
  81.   };
  82.   chrome.send(name, params);
  83. }
  84.  
  85. /**
  86.  * Returns the scale factors supported by this platform.
  87.  * @return {array} The supported scale factors.
  88.  */
  89. function getSupportedScaleFactors() {
  90.   var supportedScaleFactors = [];
  91.   if (cr.isMac || cr.isChromeOS) {
  92.     supportedScaleFactors.push(1);
  93.     supportedScaleFactors.push(2);
  94.   } else {
  95.     // Windows must be restarted to display at a different scale factor.
  96.     supportedScaleFactors.push(window.devicePixelRatio);
  97.   }
  98.   return supportedScaleFactors;
  99. }
  100.  
  101. /**
  102.  * Generates a CSS url string.
  103.  * @param {string} s The URL to generate the CSS url for.
  104.  * @return {string} The CSS url string.
  105.  */
  106. function url(s) {
  107.   // http://www.w3.org/TR/css3-values/#uris
  108.   // Parentheses, commas, whitespace characters, single quotes (') and double
  109.   // quotes (") appearing in a URI must be escaped with a backslash
  110.   var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
  111.   // WebKit has a bug when it comes to URLs that end with \
  112.   // https://bugs.webkit.org/show_bug.cgi?id=28885
  113.   if (/\\\\$/.test(s2)) {
  114.     // Add a space to work around the WebKit bug.
  115.     s2 += ' ';
  116.   }
  117.   return 'url("' + s2 + '")';
  118. }
  119.  
  120. /**
  121.  * Returns the URL of the image, or an image set of URLs for the profile avatar.
  122.  * Default avatars have resources available for multiple scalefactors, whereas
  123.  * the GAIA profile image only comes in one size.
  124.  
  125.  * @param {string} url The path of the image.
  126.  * @return {string} The url, or an image set of URLs of the avatar image.
  127.  */
  128. function getProfileAvatarIcon(path) {
  129.   var chromeThemePath = 'chrome://theme';
  130.   var isDefaultAvatar =
  131.       (path.slice(0, chromeThemePath.length) == chromeThemePath);
  132.   return isDefaultAvatar ? imageset(path + '@scalefactorx'): url(path);
  133. }
  134.  
  135. /**
  136.  * Generates a CSS -webkit-image-set for a chrome:// url.
  137.  * An entry in the image set is added for each of getSupportedScaleFactors().
  138.  * The scale-factor-specific url is generated by replacing the first instance of
  139.  * 'scalefactor' in |path| with the numeric scale factor.
  140.  * @param {string} path The URL to generate an image set for.
  141.  *     'scalefactor' should be a substring of |path|.
  142.  * @return {string} The CSS -webkit-image-set.
  143.  */
  144. function imageset(path) {
  145.   var supportedScaleFactors = getSupportedScaleFactors();
  146.  
  147.   var replaceStartIndex = path.indexOf('scalefactor');
  148.   if (replaceStartIndex < 0)
  149.     return url(path);
  150.  
  151.   var s = '';
  152.   for (var i = 0; i < supportedScaleFactors.length; ++i) {
  153.     var scaleFactor = supportedScaleFactors[i];
  154.     var pathWithScaleFactor = path.substr(0, replaceStartIndex) + scaleFactor +
  155.         path.substr(replaceStartIndex + 'scalefactor'.length);
  156.  
  157.     s += url(pathWithScaleFactor) + ' ' + scaleFactor + 'x';
  158.  
  159.     if (i != supportedScaleFactors.length - 1)
  160.       s += ', ';
  161.   }
  162.   return '-webkit-image-set(' + s + ')';
  163. }
  164.  
  165. /**
  166.  * Parses query parameters from Location.
  167.  * @param {string} location The URL to generate the CSS url for.
  168.  * @return {object} Dictionary containing name value pairs for URL
  169.  */
  170. function parseQueryParams(location) {
  171.   var params = {};
  172.   var query = unescape(location.search.substring(1));
  173.   var vars = query.split('&');
  174.   for (var i = 0; i < vars.length; i++) {
  175.     var pair = vars[i].split('=');
  176.     params[pair[0]] = pair[1];
  177.   }
  178.   return params;
  179. }
  180.  
  181. /**
  182.  * Creates a new URL by appending or replacing the given query key and value.
  183.  * Not supporting URL with username and password.
  184.  * @param {object} location The original URL.
  185.  * @param {string} key The query parameter name.
  186.  * @param {string} value The query parameter value.
  187.  * @return {string} The constructed new URL.
  188.  */
  189. function setQueryParam(location, key, value) {
  190.   var query = parseQueryParams(location);
  191.   query[encodeURIComponent(key)] = encodeURIComponent(value);
  192.  
  193.   var newQuery = '';
  194.   for (var q in query) {
  195.     newQuery += (newQuery ? '&' : '?') + q + '=' + query[q];
  196.   }
  197.  
  198.   return location.origin + location.pathname + newQuery + location.hash;
  199. }
  200.  
  201. function findAncestorByClass(el, className) {
  202.   return findAncestor(el, function(el) {
  203.     if (el.classList)
  204.       return el.classList.contains(className);
  205.     return null;
  206.   });
  207. }
  208.  
  209. /**
  210.  * Return the first ancestor for which the {@code predicate} returns true.
  211.  * @param {Node} node The node to check.
  212.  * @param {function(Node) : boolean} predicate The function that tests the
  213.  *     nodes.
  214.  * @return {Node} The found ancestor or null if not found.
  215.  */
  216. function findAncestor(node, predicate) {
  217.   var last = false;
  218.   while (node != null && !(last = predicate(node))) {
  219.     node = node.parentNode;
  220.   }
  221.   return last ? node : null;
  222. }
  223.  
  224. function swapDomNodes(a, b) {
  225.   var afterA = a.nextSibling;
  226.   if (afterA == b) {
  227.     swapDomNodes(b, a);
  228.     return;
  229.   }
  230.   var aParent = a.parentNode;
  231.   b.parentNode.replaceChild(a, b);
  232.   aParent.insertBefore(b, afterA);
  233. }
  234.  
  235. /**
  236.  * Disables text selection and dragging, with optional whitelist callbacks.
  237.  * @param {function(Event):boolean=} opt_allowSelectStart Unless this function
  238.  *    is defined and returns true, the onselectionstart event will be
  239.  *    surpressed.
  240.  * @param {function(Event):boolean=} opt_allowDragStart Unless this function
  241.  *    is defined and returns true, the ondragstart event will be surpressed.
  242.  */
  243. function disableTextSelectAndDrag(opt_allowSelectStart, opt_allowDragStart) {
  244.   // Disable text selection.
  245.   document.onselectstart = function(e) {
  246.     if (!(opt_allowSelectStart && opt_allowSelectStart.call(this, e)))
  247.       e.preventDefault();
  248.   };
  249.  
  250.   // Disable dragging.
  251.   document.ondragstart = function(e) {
  252.     if (!(opt_allowDragStart && opt_allowDragStart.call(this, e)))
  253.       e.preventDefault();
  254.   };
  255. }
  256.  
  257. /**
  258.  * Call this to stop clicks on <a href="#"> links from scrolling to the top of
  259.  * the page (and possibly showing a # in the link).
  260.  */
  261. function preventDefaultOnPoundLinkClicks() {
  262.   document.addEventListener('click', function(e) {
  263.     var anchor = findAncestor(e.target, function(el) {
  264.       return el.tagName == 'A';
  265.     });
  266.     // Use getAttribute() to prevent URL normalization.
  267.     if (anchor && anchor.getAttribute('href') == '#')
  268.       e.preventDefault();
  269.   });
  270. }
  271.  
  272. /**
  273.  * Check the directionality of the page.
  274.  * @return {boolean} True if Chrome is running an RTL UI.
  275.  */
  276. function isRTL() {
  277.   return document.documentElement.dir == 'rtl';
  278. }
  279.  
  280. /**
  281.  * Get an element that's known to exist by its ID. We use this instead of just
  282.  * calling getElementById and not checking the result because this lets us
  283.  * satisfy the JSCompiler type system.
  284.  * @param {string} id The identifier name.
  285.  * @return {!Element} the Element.
  286.  */
  287. function getRequiredElement(id) {
  288.   var element = $(id);
  289.   assert(element, 'Missing required element: ' + id);
  290.   return element;
  291. }
  292.  
  293. // Handle click on a link. If the link points to a chrome: or file: url, then
  294. // call into the browser to do the navigation.
  295. document.addEventListener('click', function(e) {
  296.   if (e.defaultPrevented)
  297.     return;
  298.  
  299.   var el = e.target;
  300.   if (el.nodeType == Node.ELEMENT_NODE &&
  301.       el.webkitMatchesSelector('A, A *')) {
  302.     while (el.tagName != 'A') {
  303.       el = el.parentElement;
  304.     }
  305.  
  306.     if ((el.protocol == 'file:' || el.protocol == 'about:') &&
  307.         (e.button == 0 || e.button == 1)) {
  308.       chrome.send('navigateToUrl', [
  309.         el.href,
  310.         el.target,
  311.         e.button,
  312.         e.altKey,
  313.         e.ctrlKey,
  314.         e.metaKey,
  315.         e.shiftKey
  316.       ]);
  317.       e.preventDefault();
  318.     }
  319.   }
  320. });
  321.  
  322. /**
  323.  * Creates a new URL which is the old URL with a GET param of key=value.
  324.  * @param {string} url The base URL. There is not sanity checking on the URL so
  325.  *     it must be passed in a proper format.
  326.  * @param {string} key The key of the param.
  327.  * @param {string} value The value of the param.
  328.  * @return {string} The new URL.
  329.  */
  330. function appendParam(url, key, value) {
  331.   var param = encodeURIComponent(key) + '=' + encodeURIComponent(value);
  332.  
  333.   if (url.indexOf('?') == -1)
  334.     return url + '?' + param;
  335.   return url + '&' + param;
  336. }
  337.  
  338. /**
  339.  * Creates a CSS -webkit-image-set for a favicon request.
  340.  * @param {string} url The url for the favicon.
  341.  * @param {number=} opt_size Optional preferred size of the favicon.
  342.  * @param {string=} opt_type Optional type of favicon to request. Valid values
  343.  *     are 'favicon' and 'touch-icon'. Default is 'favicon'.
  344.  * @return {string} -webkit-image-set for the favicon.
  345.  */
  346. function getFaviconImageSet(url, opt_size, opt_type) {
  347.   var size = opt_size || 16;
  348.   var type = opt_type || 'favicon';
  349.   return imageset(
  350.       'chrome://' + type + '/size/' + size + '@scalefactorx/' + url);
  351. }
  352.  
  353. /**
  354.  * Creates a new URL for a favicon request for the current device pixel ratio.
  355.  * The URL must be updated when the user moves the browser to a screen with a
  356.  * different device pixel ratio. Use getFaviconImageSet() for the updating to
  357.  * occur automatically.
  358.  * @param {string} url The url for the favicon.
  359.  * @param {number=} opt_size Optional preferred size of the favicon.
  360.  * @param {string=} opt_type Optional type of favicon to request. Valid values
  361.  *     are 'favicon' and 'touch-icon'. Default is 'favicon'.
  362.  * @return {string} Updated URL for the favicon.
  363.  */
  364. function getFaviconUrlForCurrentDevicePixelRatio(url, opt_size, opt_type) {
  365.   var size = opt_size || 16;
  366.   var type = opt_type || 'favicon';
  367.   return 'chrome://' + type + '/size/' + size + '@' +
  368.       window.devicePixelRatio + 'x/' + url;
  369. }
  370.  
  371. /**
  372.  * Creates an element of a specified type with a specified class name.
  373.  * @param {string} type The node type.
  374.  * @param {string} className The class name to use.
  375.  * @return {Element} The created element.
  376.  */
  377. function createElementWithClassName(type, className) {
  378.   var elm = document.createElement(type);
  379.   elm.className = className;
  380.   return elm;
  381. }
  382.  
  383. /**
  384.  * webkitTransitionEnd does not always fire (e.g. when animation is aborted
  385.  * or when no paint happens during the animation). This function sets up
  386.  * a timer and emulate the event if it is not fired when the timer expires.
  387.  * @param {!HTMLElement} el The element to watch for webkitTransitionEnd.
  388.  * @param {number} timeOut The maximum wait time in milliseconds for the
  389.  *     webkitTransitionEnd to happen.
  390.  */
  391. function ensureTransitionEndEvent(el, timeOut) {
  392.   var fired = false;
  393.   el.addEventListener('webkitTransitionEnd', function f(e) {
  394.     el.removeEventListener('webkitTransitionEnd', f);
  395.     fired = true;
  396.   });
  397.   window.setTimeout(function() {
  398.     if (!fired)
  399.       cr.dispatchSimpleEvent(el, 'webkitTransitionEnd');
  400.   }, timeOut);
  401. }
  402.  
  403. /**
  404.  * Alias for document.scrollTop getter.
  405.  * @param {!HTMLDocument} doc The document node where information will be
  406.  *     queried from.
  407.  * @return {number} The Y document scroll offset.
  408.  */
  409. function scrollTopForDocument(doc) {
  410.   return doc.documentElement.scrollTop || doc.body.scrollTop;
  411. }
  412.  
  413. /**
  414.  * Alias for document.scrollTop setter.
  415.  * @param {!HTMLDocument} doc The document node where information will be
  416.  *     queried from.
  417.  * @param {number} value The target Y scroll offset.
  418.  */
  419. function setScrollTopForDocument(doc, value) {
  420.   doc.documentElement.scrollTop = doc.body.scrollTop = value;
  421. }
  422.  
  423. /**
  424.  * Alias for document.scrollLeft getter.
  425.  * @param {!HTMLDocument} doc The document node where information will be
  426.  *     queried from.
  427.  * @return {number} The X document scroll offset.
  428.  */
  429. function scrollLeftForDocument(doc) {
  430.   return doc.documentElement.scrollLeft || doc.body.scrollLeft;
  431. }
  432.  
  433. /**
  434.  * Alias for document.scrollLeft setter.
  435.  * @param {!HTMLDocument} doc The document node where information will be
  436.  *     queried from.
  437.  * @param {number} value The target X scroll offset.
  438.  */
  439. function setScrollLeftForDocument(doc, value) {
  440.   doc.documentElement.scrollLeft = doc.body.scrollLeft = value;
  441. }
  442.  
  443. /**
  444.  * Replaces '&', '<', '>', '"', and ''' characters with their HTML encoding.
  445.  * @param {string} original The original string.
  446.  * @return {string} The string with all the characters mentioned above replaced.
  447.  */
  448. function HTMLEscape(original) {
  449.   return original.replace(/&/g, '&')
  450.                  .replace(/</g, '<')
  451.                  .replace(/>/g, '>')
  452.                  .replace(/"/g, '"')
  453.                  .replace(/'/g, ''');
  454. }
  455.  
  456. /**
  457.  * Shortens the provided string (if necessary) to a string of length at most
  458.  * |maxLength|.
  459.  * @param {string} original The original string.
  460.  * @param {number} maxLength The maximum length allowed for the string.
  461.  * @return {string} The original string if its length does not exceed
  462.  *     |maxLength|. Otherwise the first |maxLength| - 1 characters with '...'
  463.  *     appended.
  464.  */
  465. function elide(original, maxLength) {
  466.   if (original.length <= maxLength)
  467.     return original;
  468.   return original.substring(0, maxLength - 1) + '\u2026';
  469. }
  470.